import os

import pyperclip
from tkinter import Frame, Label, Button
from tkinter import ttk
from tkinter import W,E,S,N

from CommonOperations.parse_SQLite import ParseSQLite
from CustomWidget.custom_button import CustomButtonPair


class HistoryFrame(Frame):
    """图片历史记录窗口"""
    def __init__(self, master):
        self.root = master
        self.root.config()
        self.root.title("历史记录")
        # self.root.geometry("400x400")

        super(HistoryFrame, self).__init__(master)
        self.grid()
        self.create_widgets()

    def create_widgets(self):
        # 新建图片切换按钮
        self.history_menu = Label(self, text="历史记录", justify='center', width=25, background='#F5F5F5')
        self.history_menu.grid(row=1, column=1, sticky=W, columnspan=2)
        self.create_img_button = Button(self, text="创建图片", command=self.change_new_img_frame, width=25)
        self.create_img_button.grid(row=1, column=3, sticky=W, columnspan=2)

        # 图片列表只能单选
        self.history_images = ttk.Treeview(self,
                                           height=15,
                                           columns=['1', '2', '3', '4'],
                                           selectmode="browse",
                                           show='headings')
        self.history_images.heading('1', text="宽")
        self.history_images.heading('2', text="高")
        self.history_images.heading('3', text="格式")
        self.history_images.heading('4', text="内容")

        self.history_images.column('1', width=40, anchor='e')
        self.history_images.column('2', width=40, anchor='e')
        self.history_images.column('3', width=40, anchor='e')
        self.history_images.column('4', width=380, anchor='e')

        self.get_all_created_images()
        self.history_images.grid(row=9, column=1, sticky=W, columnspan=4, padx=2)
        self.history_images.bind('<ButtonRelease-1>', self.get_path())

        lf = self.get_all_created_images
        rf = self.get_path
        self.buttons = CustomButtonPair(self, 10, "刷新列表", lf, "复制选中路径", rf, pady=10)

    def get_path(self):
        """选中的文件路径复制到系统剪切板"""
        img_ID_origin = self.history_images.selection()
        try:
            img_ID = int(img_ID_origin[0])
            select_single_img_path = ParseSQLite().select_table_data("image_history", ["img_save_path"], search_key="id", search_value=img_ID, num=1)
            full_choose_img_path = select_single_img_path[0][0]
        except:
            full_choose_img_path = ""

        # 复制到剪切板
        pyperclip.copy(full_choose_img_path)

    def get_all_created_images(self):
        """从SQLite获取图片记录"""
        # 清空列表
        all_tree_item = self.history_images.get_children()
        for i in all_tree_item:
            self.history_images.delete(i)

        # 从SQLite获取图片记录
        img_histories = ParseSQLite().select_table_data("image_history", ["id", "img_width", "img_height", "img_type", "img_desc"], num=50)
        for history in img_histories:
            self.history_images.insert(parent='', index='end', values=(history[1], history[2], history[3], history[4]), iid=history[0])

    def get_all_created_images_from_file(self):
        """获取文件目录"""
        # 图片文件夹
        created_pictures_dir = os.path.join(os.getcwd(), 'TestImages')
        all_origin_images = os.listdir(created_pictures_dir)

        # 去除非图片文件
        all_created_images = []
        for f in all_origin_images:
            if f.endswith("jpg") or f.endswith("png") or f.endswith("gif"):
                file_path = os.path.join(created_pictures_dir, f)
                all_created_images.append(file_path)

        all_created_images.sort(key=lambda i: os.path.getctime(i), reverse=True)

        # 清空列表
        all_tree_item = self.history_images.get_children()
        for i in all_tree_item:
            self.history_images.delete(i)

        # 重新插入更新后的数据
        for img in all_created_images:
            show_name = os.path.split(img)
            show_type = os.path.splitext(img)
            self.history_images.insert('', 'end', values=(show_type[-1].replace('.', ''), show_name[-1]))

    def change_new_img_frame(self):
        """切换到新建图片窗口"""
        self.destroy()
        from PageFrames.create_new_img_frame import CreateNewImageFrame

        CreateNewImageFrame(self.root)
